package cn.edu.zjicm.wordsnet_d.media;

import java.io.File;
import java.io.IOException;
import android.content.Context;
import android.media.MediaPlayer;
import android.util.Log;

import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;

public class VoicePlayer {
	
	private static VoicePlayer mInstance;
	private MediaPlayer mMediaPlayer;
	private Context context;
	
	private VoicePlayer(Context context){
		this.context = context;
		mMediaPlayer = new MediaPlayer();
	}
	
	public static VoicePlayer getInstance(Context context){
		if(mInstance == null){
			mInstance = new VoicePlayer(context);
		}
		return mInstance;
	}
	
	public boolean play(OneWord word) {		
		if(FileManager.isVoiceFileExist(context, word)){
			//Log.d("VoicePlayer", "play:" + lemma);
			File voiceFile = FileManager.getVoiceFile(word);
			playVoice(voiceFile);
			return true;
		}

		Log.e("VoicePlayer", "voice file not found:" + word.getLemma());
		return false;
	}
	
	/**
	 * 在喇叭的显示时已经判断音频是否存在了
	 * @param word
	 */
	public void playWithNoCheckVoiceFile(OneWord word){
		File voiceFile = FileManager.getVoiceFile(word);
		playVoice(voiceFile);
	}
	
	public void playVoice(File voiceFile){
		try {
			mMediaPlayer.reset();
			mMediaPlayer.setDataSource(voiceFile.getAbsolutePath());
			mMediaPlayer.prepare();
			mMediaPlayer.start();			
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void releaseMediaPlayer(){
		if(mMediaPlayer!=null){
			if(mMediaPlayer.isPlaying()){
				mMediaPlayer.stop();
				mMediaPlayer.release();
				mMediaPlayer = null;
				mInstance = null;
			}
		}
	}
	
}

/*
public class VoiceDownloaderActivity extends Activity {
	private static MediaPlayer mp = null;

	public static void play(String lemma) {
		MediaPlayer mp = null;
		try {
			mp = new MediaPlayer();
			File f = new File("/sdcard/iwordnet/voice/" + lemma.substring(0, 1)
					+ "/" + lemma + StaticDate.VOICE_FILE_SUFFIX_NAME);
			if (f.exists()) {
				mp.setDataSource(f.getAbsolutePath());
				mp.prepare();
				mp.start();			
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		mp.setOnCompletionListener(new OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer mp) {
				//mp.stop();
				mp.release();
			}
		});
	}
}
*/
